package com.cloud.util;

import com.alibaba.fastjson.JSONObject;
import com.cloud.entity.UploadFileEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.cloud.util.MediaUtil.getMediaType;

/**
 * @author Henry.Song
 * @version 2020/11/25
 * @description 上传文件处理工具类
 */
public class UploadUtil
{
    public static final String UPLOAD_NAME = "upload.name";
    public static final String UPLOAD_PATH = "upload.path";
    public static final String UPLOAD_MD5 = "upload.md5";
    public static final String UPLOAD_CONTENT_TYPE = "upload.content_type";
    public static final String UPLOAD_SIZE = "upload.size";

    public static List<UploadFileEntity> filesFromServlet(HttpServletRequest request) {
        List<UploadFileEntity> uploadFiles = new ArrayList<UploadFileEntity>();
        String[] uploadNames = request.getParameterValues(UPLOAD_NAME);
        if (uploadNames != null) {
            String[] uploadPaths = request.getParameterValues(UPLOAD_PATH);
            String[] uploadMD5s = request.getParameterValues(UPLOAD_MD5);
            String[] uploadSizes = request.getParameterValues(UPLOAD_SIZE);
            for(int i = 0; i < uploadNames.length; i ++) {
                UploadFileEntity entity = new UploadFileEntity();
                entity.setFileName(uploadNames[i]);
                entity.setFileType(getMediaType(uploadNames[i]));
                entity.setCheckSum(uploadMD5s[i]);
                entity.setOriginFilePath(uploadPaths[i]);
                entity.setFileSize(Integer.valueOf(uploadSizes[i]));
                uploadFiles.add(entity);
            }
        }
        return uploadFiles;
    }

    public static boolean renameFiles(JSONObject file, String storePath) {
        if (file != null) {
            String originFilePath = file.getString("originFilePath");
            String fileName = file.getString("fileName");
            File srcFile = new File(originFilePath);
            File destFile = new File(storePath, fileName);

            if (srcFile.exists() && srcFile.isFile()) {
                srcFile.renameTo(destFile);
                // 保存路径
                file.put("filePath", destFile.getAbsolutePath());
                return true;
            }
        }
        return false;
    }

    public static List<UploadFileEntity> renameFiles(List<UploadFileEntity> uploadFiles, String storePath) {
        List<UploadFileEntity> storedFiles = new ArrayList<UploadFileEntity>();
        for(UploadFileEntity file : uploadFiles) {
            boolean status = renameFiles(file, storePath);
            if (status) {
                storedFiles.add(file);
            }
        }
        return storedFiles;
    }
}
